auto.waitFor()
images.requestScreenCapture()

function createExecutor(processorListCreator) {
    var processorList = processorListCreator()
    function processOneCommand(cmd) {
        for (var processor of processorList) {
            var regexExpr = processor[0]
            var f = processor[1]
            var matcher = cmd.match(regexExpr)
            if (matcher) {
                console.log(`执行: ${cmd}`)
                try { f.apply(f, matcher)
                } catch (e) { console.error(e) }
                return
            }
        }
        console.log(`无法识别的命令: ${cmd}`)
    }
    return allCmd => allCmd.split('\n').map(s => s.trim()).filter(s => s).filter(s => !s.startsWith('#')).map(processOneCommand)
}

var executor = createExecutor(() => {
    var sleepMs = 2000
    function captureScreenSnapshot() { withImage(() => images.captureScreen(), img => images.save(img, `截屏_${new Date().toJSON().replace(/[:\-Z]/g, '').replace('T', '-').replace('.', '-')}.png`)) }
    function beforeExec() { }
    function afterExec() { sleep(sleepMs) }
    function wrapExecHook(list) {
        return list.map(pair => {
            var f = pair[1]
            return [pair[0], function() {
                beforeExec.apply(beforeExec, arguments)
                f.apply(f, arguments)
                afterExec.apply(afterExec, arguments)
            }]
        })
    }
    function withImage(createF, usingF) {
        var img = createF()
        var result = usingF(img)
        img.recycle()
        return result
    }
    function withImageList(createFList, usingF) {
        var imgList = createFList.map(createF => createF())
        var result = usingF(imgList)
        imgList.map(img => img.recycle())
        return result
    }
    function wrapCaptureScreenSnapshot(f) {
        return function () {
            captureScreenSnapshot()
            var result = f.apply(f, arguments)
            captureScreenSnapshot()
            return result
        }
    }
    function getRegion(regionType) {
        var halfWidth = device.width / 2
        var halfHeight = device.height / 2
        if (regionType == '左上') { return [0, 0, halfWidth, halfHeight] } 
        else if (regionType == '左下') { return [0, halfHeight, halfWidth, halfHeight] } 
        else if (regionType == '右上') { return [halfWidth, 0, halfWidth, halfHeight] } 
        else if (regionType == '右下') { return [halfWidth, halfHeight, halfWidth, halfHeight] } 
        else { return [] }
    }
    function tryFindImage(tryCount, imgPath, onFounded, onNotFounded, regionType) {
        function findImageInImgList(screenImg, imgList) {
            for (var img of imgList) {
                var pt = images.findImage(screenImg, img, {region: getRegion(regionType)})
                if (pt) {
                    return [pt, img]
                }
            }
        }
        withImageList(imgPath.split(',').map(path => () => images.read(path)), imgList => {
            for (var i = 0; i < tryCount; ++i) {
                var founded = withImage(() => images.captureScreen(), screenImg => {
                    var ptAndImg = findImageInImgList(screenImg, imgList)
                    if (!ptAndImg) {
                        console.log(`${i+1}/${tryCount} 未找到图片${imgPath}`)
                        onNotFounded && onNotFounded()
                        return false
                    }
                    var pt = ptAndImg[0]
                    var img = ptAndImg[1]
                    console.log(`找到图片${imgPath}`)
                    onFounded && onFounded(pt, img)
                    return true
                })
                if (founded) return
                sleep(sleepMs)
            }
            console.log(`始终找不到图片${imgPath}`)
        })
    }
    function _clickImageCenter(pt, img, pressMilliSecond) {
        var x = Math.round(pt.x + (img.getWidth() / 2) + (random(-2, 2)), 0)
        var y = Math.round(pt.y + (img.getHeight() / 2) + (random(-2, 2)), 0)
        var result = press(x, y, pressMilliSecond)
        console.log(`点击(${x},${y}) ${pressMilliSecond}ms 结果=${result}`)
    }
    function clickImageCenter(pt, img) { _clickImageCenter(pt, img, 200) }
    function longClickImageCenter(pt, img) { _clickImageCenter(pt, img, 3000) }
    function swipeUp() {
        var x = device.width / 2
        var y1 = device.height / 3 * 2
        var y2 = device.height / 3 * 1
        return swipe(x, y1, x, y2, 500)
    }
    function swipeDown() {
        var x = device.width / 2
        var y1 = device.height / 3 * 1
        var y2 = device.height / 3 * 2
        return swipe(x, y1, x, y2, 500)
    }
    return wrapExecHook([
        [ '^启动应用(.*)$', function() { launchApp(arguments[1]) }],
        [ '^设置默认延时(\\d+)ms$', function() { sleepMs = arguments[1] - 0 }],
        [ '^延时(\\d+)ms$', function() { sleep(arguments[1] - 0) }],
        [ '^延时(\\d+)s$', function() { sleep((arguments[1] - 0) * 1000) }],
        [ '^返回$', function() { back() }],
        [ '^回到桌面$', function() { home() }],
        [ '^最近运行的程序$', function() { recents() }],
        [ '^尝试(\\d+)次等待图片 (.*) 出现(在(.*))?并点击图片$', wrapCaptureScreenSnapshot(function() { tryFindImage(arguments[1] - 0, arguments[2], clickImageCenter, null, arguments[4]) })],
        [ '^尝试(\\d+)次等待图片 (.*) 出现(在(.*))?并长按图片$', wrapCaptureScreenSnapshot(function() { tryFindImage(arguments[1] - 0, arguments[2], longClickImageCenter, null, arguments[4]) })],
        [ '^尝试(\\d+)次向下滑动直到图片 (.*) 出现(在(.*))?$', wrapCaptureScreenSnapshot(function () { tryFindImage(arguments[1] - 0, arguments[2], null, swipeUp, arguments[4]) })],
        [ '^设置剪切板内容 (.*)$', function () { setClip(arguments[1]) }],
        [ '^截屏$', captureScreenSnapshot ],
    ])
})